﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using yq.CacheHelp;
using yq.IBase.Basis;

namespace yq.IBase.Cache
{
    internal class CacheManage
    {
        /// <summary>
        /// 锁
        /// </summary>
        static object lockobj = new object();
        
        /// <summary>
        /// 缓存关联
        /// </summary>
        static Dictionary<string, IList<DefaultCache>> cacheLink = new Dictionary<string, IList<DefaultCache>>();

        /// <summary>
        /// 关联绑定
        /// </summary>
        /// <param name="types"></param>
        /// <param name="cache"></param>
        public static void Bind(IList<Type> types,DefaultCache cache)
        {
            var list = types.Select(obj => obj.FullName).ToList();
            lock (lockobj)
            {
                foreach (var key in list)
                {
                    if (cacheLink.ContainsKey(key))
                    {
                        cacheLink[key].Add(cache);
                    }
                    else
                    {
                        cacheLink.Add(key, new List<DefaultCache>(){cache});
                    }
                }
            }
        }

        /// <summary>
        /// 执行刷新缓存
        /// </summary>
        /// <returns></returns>
        public static void Refresh(CaCheRefresh refresh)
        {
            foreach (var key in refresh.Get())
            {
                if (cacheLink.ContainsKey(key))
                {
                    foreach (var val in cacheLink[key])
                     {
                         val.Delete(key);
                     }
                }
            }
        }

        /// <summary>
        /// 日志
        /// </summary>
        /// <param name="log"></param>
        /// <param name="list"></param>
        /// <param name="tp"></param>
        /// <param name="errorMsg"></param>
        public static void Log(LogMsg log,IList<string> list, TimeSpan tp, string errorMsg = "")
        {
            if (log != null)
            {
                log.SqlList = list;
                log.Tp = tp;
                log.Error = errorMsg;
            }
        }

    }
}
